
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import org.json.me.JSONArray;
import org.json.me.JSONObject;
import javax.microedition.lcdui.*;

public class Categories extends ListView implements CommandListener {

    private Command back = new Command("Back", Command.BACK, 0);
    private int type;

    public Categories() {
        addCommand(back);
        setCommandListener(this);
    }

    public void load(String url, int type) {
        String[] label;
        String[] value;
        try {
            HttpConnection hc = (HttpConnection) Connector.open(AppManager.SERVER + url);
            InputStream is = hc.openInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            char[] data = new char[1];
            String str_json = "";
            while (isr.read(data) != -1) {
                str_json += new String(data);
            }
            hc.close();
            JSONArray ja = new JSONArray(str_json);
            label = new String[ja.length() - 1];
            value = new String[ja.length() - 1];
            JSONObject jo;
            for (int i = 0; i < ja.length() - 1; i++) {
                jo = ja.getJSONObject(i);
                label[i] = jo.getString("cat_name");
                value[i] = jo.getString("cat_id");
            }
            if (type == 0) {
                this.type = type;
                this.setImage("/genres_s.png");
                this.title = "Thể loại";
            } else if (type == 1) {
                this.type = type;
                this.setImage("/singer_s.png");
                this.title = "Ca sĩ";
            }
            this.loadItems(label, value);
        } catch (Exception ex) {
        }
    }

    public void onSelect(int selectedIndex) {
        if (type == 1) {
            f_readsong frm1 = new f_readsong(0);
            frm1.load("search.php?singerid=" + this.value[selectedIndex]);
            frm1.title = label[selectedIndex];
            f_readplaylist frm2 = new f_readplaylist(0);
            frm2.load("search.php?type=playlist&singerid=" + this.value[selectedIndex]);
            frm2.title = label[selectedIndex];
            AppManager.open(frm1, frm2, true);
        } else if (type == 0) {
            f_readsong frm1 = new f_readsong(0);
            frm1.load("search.php?genres=" + this.value[selectedIndex]);
            frm1.title = label[selectedIndex];
            f_readplaylist frm2 = new f_readplaylist(0);
            frm2.load("search.php?type=playlist&genres=" + this.value[selectedIndex]);
            frm2.title = label[selectedIndex];
            AppManager.open(frm1, frm2, true);
        }
    }

    public void commandAction(Command c, Displayable d) {
        if (c == back) {
            AppManager.back();
        }
    }
}
